<template>
  <div class="no-background-container">
    <el-affix :offset="0">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">
            {{ routeName }}
          </div>
        </div>
        <div class="header-query">
          <div class="header-query-buttons">
            <el-button type="primary" @click="handleAddMultiple">批量添加</el-button>
            <el-button type="primary" @click="handleImport">批量导入</el-button>
            <el-button type="primary" @click="fetchData">刷新</el-button>
          </div>
          <query-form-component
            :list-loading="listLoading"
            :query-form="queryForm"
            :search-params="searchParams()"
            @submit="queryData"
            @update:query-form="updateQueryForm"
          />
        </div>
      </div>
    </el-affix>

    <player-table
      :finally-columns="finallyColumns"
      :layout="layout"
      :list="list"
      :list-loading="listLoading"
      :query-form="queryForm"
      :total="total"
      @handle-current-change="handleCurrentChange"
      @handle-delete="handleDelete"
      @handle-sign-in="handleSignIn"
      @handle-size-change="handleSizeChange"
      @update:query-form="updateQueryForm"
    >
      <template #hotelCheckinInfo="{ row }">
        <div v-if="row.hotelCheckinInfo && row.hotelCheckinInfo.length > 0">
          <el-tag
            v-for="(item, index) in row.hotelCheckinInfo"
            :key="index"
            effect="light"
            style="margin-right: 5px"
            :type="item.checkinStatus ? 'success' : 'warning'"
          >
            <i-ep-house />
            {{ item.checkinStatus ? '住宿已签到' : '住宿未签到' }} (房间: {{ item.houseNumber }})
          </el-tag>
        </div>
        <span v-else>-</span>
      </template>
    </player-table>

    <!-- 导入弹窗 -->
    <import-dialog
      ref="importDialogRef"
      :activity-id="queryForm.activityId"
      :import-url="`/api/player/import`"
      :template-api-url="`/api/player/import/template`"
      :template-file-name="`参会人导入模板.xlsx`"
      title="批量导入参会人"
      @success="handleImportSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onActivated, onBeforeMount, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PlayerTable from './components/table.vue'
import { searchParams, tableColumns } from './config'
import Public from '/@/api/public'
import ImportDialog from '/@/components/ImportDialog/index.vue'

// API路径常量
const moduleApi = '/api/player'

// 类型定义
interface QueryForm {
  page: number
  limit: number
  activityId?: string
  [key: string]: any
}

interface ApiResponse<T> {
  code: number
  message: string
  result: {
    人员列表数据: {
      count: number
      rows: T[]
    }
    应签数: number
    签到数: number
    待签数: number
    请假数: number
  }
}

interface Person {
  id: string
  name: string
  mobile: string
  isLeave: boolean
  [key: string]: any
}

// 状态管理
const list = ref<Person[]>([])
const listLoading = ref(true)
const layout = ref('total, sizes, prev, pager, next, jumper')
const total = ref(0)
const queryForm = ref<QueryForm>({
  page: 1,
  limit: 20,
})
const importDialogRef = ref()

// 路由相关
const route = useRoute()
const routeName = computed(() => route.meta.title || '')
const router = useRouter()

// 计算属性
const finallyColumns = computed(() => tableColumns.value)

// 数据操作方法
const fetchData = async () => {
  listLoading.value = true
  console.log(queryForm.value)
  if (queryForm.value.postsId) {
    queryForm.value.postsId = queryForm.value.postsId.join(',')
  }
  try {
    const response = await Public.getDetailApi({ url: moduleApi, params: queryForm.value })
    const { code, result } = response as unknown as ApiResponse<Person>
    if (code === 0) {
      list.value = result.人员列表数据.rows
      total.value = result.人员列表数据.count
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    listLoading.value = false
  }
}

// 批量导入相关方法
const handleImport = () => {
  importDialogRef.value.open()
}

const handleImportSuccess = () => {
  fetchData()
}

const handleDelete = async (id: string) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await Public.delApi({ url: moduleApi, id })
    ElMessage.success('删除成功!')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSignIn = async (employeesUserId: string) => {
  try {
    await ElMessageBox.confirm('此操作将进行手动签到, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const activityId = localStorage.getItem('hongyouActId')
    await Public.signInApi({
      url: '/api/checkins',
      data: { employeesUserId, activityId },
    })
    ElMessage.success('签到成功!')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('签到失败:', error)
      ElMessage.error('签到失败')
    }
  }
}

// 分页操作
const updateQueryForm = (newQueryForm: QueryForm) => {
  queryForm.value = { ...newQueryForm }
}

const handleSizeChange = (value: number) => {
  updatePagination({ page: 1, limit: value })
}

const handleCurrentChange = (value: number) => {
  updatePagination({ page: value })
}

const updatePagination = (params: Partial<QueryForm>) => {
  Object.assign(queryForm.value, params)
  fetchData()
}

const queryData = () => {
  updatePagination({ page: 1 })
}

// 初始化
const initialize = () => {
  const activityId = localStorage.getItem('hongyouActId')
  if (activityId) {
    queryForm.value.activityId = activityId
  }
  fetchData()
}

// 生命周期钩子
onBeforeMount(() => {
  initialize()
})

onActivated(() => {
  fetchData()
})

// 跳转到批量添加页面
const handleAddMultiple = () => {
  router.push({
    name: 'PersonSelect',
    query: {
      activityId: localStorage.getItem('hongyouActId'),
    },
  })
}
</script>

<style scoped>
.header-query {
  display: flex;
  gap: 16px;
  align-items: center;
}

.header-query-buttons {
  display: flex;
  gap: 8px;
}
</style>
